package com.fm.financemanage.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @Description: ip地址获取工具类
 */
public class IpUtil {

    private static final String UNKNOWN = "unknown";
    private static final String IP = "0:0:0:0:0:0:0:1";

    public static String getIp(HttpServletRequest request) {
        String xIp = request.getHeader("X-Real-IP");
        String xFor = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(xFor) && !UNKNOWN.equalsIgnoreCase(xFor)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = xFor.indexOf(",");
            if (index != -1) {
                return xFor.substring(0, index);
            } else {
                return xFor;
            }
        }
        xFor = xIp;
        if (StringUtils.isNotEmpty(xFor) && !UNKNOWN.equalsIgnoreCase(xFor)) {
            return xFor;
        }
        if (StringUtils.isBlank(xFor) || UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(xFor) || UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(xFor) || UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(xFor) || UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(xFor) || UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getRemoteAddr();
        }
        if (IP.equals(xFor)) {
            xFor = "127.0.0.1";
        }
        return xFor;
    }

    private static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs != null && (strLen = cs.length()) != 0) {
            for (int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }
    /**
     * 获取 HttpClient
     *
     * @param url
     * @return
     */
    private static HttpClient wrapClient(String url) {
        HttpClient httpClient = HttpClientBuilder.create().build();
        if (url != null && url.startsWith("https://")) {
            return getSslClient();
        }
        return httpClient;
    }

    private static HttpClient getSslClient() {
        try {
            SSLContext sslContext = SSLContextBuilder.create().setProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
            RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
            return HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
    /**   根据ip地址获取真是地址
     * @Author zpc
     * @Date 15:57 2021/2/22
     * @Param [ip]
     * @return java.lang.String
     **/
    public static String getRealAdder(String ip) {
        HttpClient httpClient = wrapClient("http://whois.pconline.com.cn/ipJson.jsp?ip="+ip+"&json=true");
        HttpPost httpPost = new HttpPost("http://whois.pconline.com.cn/ipJson.jsp?ip="+ip+"&json=true");
        // 得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        try {
            HttpResponse execute = httpClient.execute(httpPost);
            String result = EntityUtils.toString(execute.getEntity(), "UTF-8");
            Map map = JSONObject.parseObject(result, Map.class);
            Object addr = map.get("city");
            return TextUtil.isEmpty(addr)?"":addr.toString();
        } catch (IOException e) {
        }
        return "";
    }
    public static void main(String[] args) throws IOException {
        String realAdder = getRealAdder("127.0.0.1");

    }
}
